package com.bnlr.lrparking.widget.boarddialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.VerifyCodeM;
import com.bnlr.lrparking.util.CountDownTimerUtils;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义弹框dialog
 */

public class KeyBoardDialog extends Dialog{

    private Context context;
    private RecyclerView mRecyclerView;
    private RelativeLayout mClose;
    private TextView tvSure;
    private ArrayList<Map<String, String>> valueList = new ArrayList<>();
    private KeyBoardAdapter adapter;
    private EditText tvPhone,board_verify;
    private ImageView ivRight,iv_back;
    private LinearLayout llOne,llTwo;
    private TextView tvVerify;
    private OnDialogResultListener onDialogResultListener;
    private String oldPhone;
    private TextView tvTwoHint;
    private CountDownTimerUtils mCountDownTimerUtils;
    private String message_code;
    public KeyBoardDialog(Context context, String phone) {
        super(context, R.style.Theme_Dialog_From_Bottom);
        this.context=context;
        oldPhone = phone;
        setContentView(R.layout.key_board_layout);
        initValueList();
        initComponent();
        adapter = new KeyBoardAdapter(context,valueList);
        mRecyclerView.setAdapter(adapter);
        init();
        initListener();
    }

    public void setOnDialogResultListener(OnDialogResultListener onDialogResultListener) {
        this.onDialogResultListener = onDialogResultListener;
    }

    private void initListener() {
        adapter.setmOnItemClickListener(new KeyBoardAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position != 9 && position != 11) {
                    if (llOne.getVisibility() == View.VISIBLE) {
                        String num = valueList.get(position).get("name");
                        tvPhone.append(num);
                        if (RegexUtils.isMobileExact(tvPhone.getText().toString())) {
                            ivRight.setVisibility(View.VISIBLE);
                            tvSure.setEnabled(true);
                        } else {
                            tvSure.setEnabled(false);
                        }
                    } else {
                        String num = valueList.get(position).get("name");
                        board_verify.append(num);
                        if (board_verify.getText().toString().length() == 6) {
                            verifyY(board_verify.getText().toString());

                        }
                    }
                } else if (position == 11) {
                    dismiss();
                    onDialogResultListener.onResult("fail");
                }
            }
        });
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (llOne.getVisibility() == View.VISIBLE) {

                    if (!"".equals(tvPhone.getText().toString())) {
                        tvPhone.setText(tvPhone.getText().toString().substring(0, tvPhone.getText().toString().length() - 1));
                        tvPhone.setSelection(tvPhone.getText().toString().length() );
                        ivRight.setVisibility(View.GONE);
                        tvSure.setEnabled(false);
                    }
                } else {
                    if (!"".equals(board_verify.getText().toString())) {
                        board_verify.setText(board_verify.getText().toString().substring(0, board_verify.getText().toString().length() - 1));
                    }
                }
            }
        });
        mClose.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (llOne.getVisibility() == View.VISIBLE) {
                    tvPhone.setText("");
                    tvPhone.setSelection(tvPhone.getText().toString().length() );
                    ivRight.setVisibility(View.GONE);
                } else {
                    board_verify.setText("");
                }
                return true;
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newPhone = tvPhone.getText().toString();
                if (newPhone.equals(oldPhone)) {
                    dismiss();
                    onDialogResultListener.onResult("some");
                    return;
                } else {
                    llOne.setVisibility(View.GONE);
                    llTwo.setVisibility(View.VISIBLE);
                    tvSure.setEnabled(false);
                    //发送验证码
                    SendYzm();
                }

            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llOne.setVisibility(View.VISIBLE);
                llTwo.setVisibility(View.GONE);
                board_verify.setText("");
                tvSure.setEnabled(true);
                if (mCountDownTimerUtils !=null) {
                    mCountDownTimerUtils.cancel();
                }
                tvVerify.setEnabled(true);
                tvVerify.setText("重新获取");
            }
        });
        tvVerify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendYzm();
            }
        });
        tvPhone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        //禁止光标移动
                        if (tvPhone.getText().toString().length() >0) {
                            tvPhone.setSelection(tvPhone.getText().toString().length());
                        }
                        break;
                }
                return true;
            }
        });
    }

    private void initComponent() {
        mRecyclerView = (RecyclerView) findViewById(R.id.key_board_rv);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context,3));
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(context,1,R.color.text_hint));
        mClose = (RelativeLayout) findViewById(R.id.key_board_close);
        tvSure = (TextView) findViewById(R.id.key_board_sure);
        tvPhone = (EditText) findViewById(R.id.board_phone);
        ivRight = (ImageView) findViewById(R.id.iv_verify_phone);
        tvPhone.setText(oldPhone);
        ivRight.setVisibility(View.VISIBLE);
        forbidKeyBoard();
        configFocusable();
        tvPhone.setSelection(tvPhone.getText().toString().length());
        board_verify = (EditText) findViewById(R.id.board_verify);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        llOne = (LinearLayout) findViewById(R.id.dialog_ll_one);
        llTwo = (LinearLayout) findViewById(R.id.dialog_ll_two);
        tvVerify = (TextView) findViewById(R.id.tv_verifica);
        tvTwoHint = (TextView) findViewById(R.id.board_two_hint);
    }

    private void init() {
        this.setCanceledOnTouchOutside(true);
        this.setCancelable(true);
        Window window = this.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.ios_bottom_dialog_anim);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }
    private void initValueList() {
        // 初始化按钮上应该显示的数字
        for (int i = 1; i < 13; i++) {
            Map<String, String> map = new HashMap<>();
            if (i < 10) {
                map.put("name", String.valueOf(i));
            } else if (i == 10) {
                map.put("name", "");
            } else if (i == 11) {
                map.put("name", String.valueOf(0));
            } else if (i == 12) {
                map.put("name", "");
            }
            valueList.add(map);
        }
    }

    @Override
    public void show() {
        super.show();
    }

    public interface OnDialogResultListener {
        void onResult(String result);
    }

    /**
     * 发送验证码
     */
    private void SendYzm() {
        try {
            Request<String>  mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "sendValidateMCD");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", tvPhone.getText().toString());
            mRequest.add("flag", "0");
            // 添加到请求队列
            CallServer.getRequestInstance().add(context, mRequest,
                    new CustomHttpListener<VerifyCodeM>(context, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {
                           //{"msgcode":"1","msg":"成功","data":{"code":"06641"}}
                                if ("1".equals(code)) {
                                    message_code = data.getData().getCode();
                                    setVerifica(tvVerify);
                                    tvTwoHint.setTextColor(Color.parseColor("#999999"));
                                    tvTwoHint.setText("验证码已发  " + tvPhone.getText().toString());
                                } else {
                                    tvVerify.setEnabled(true);
                                    tvVerify.setText("重新获取");
                                    tvTwoHint.setTextColor(Color.parseColor("#ea5544"));
                                    tvTwoHint.setText("验证码发送失败");
                                }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    /**
     * 验证验证码
     */
    private void verifyY(String code) {
        try {
            Request<String>  mRequest = NoHttp.createStringRequest(Urls.COMMON, LrConstant.POST);
            mRequest.add("action", "ValidMsgCode");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", tvPhone.getText().toString());
            mRequest.add("code", code);
            // 添加到请求队列
            CallServer.getRequestInstance().add(context, mRequest,
                    new CustomHttpListener<BaseArrayBean>(context, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            //{"msgcode":"1","msg":"成功","data":{"code":"06641"}}

                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    dismiss();
                                    onDialogResultListener.onResult(tvPhone.getText().toString());
                                } else {
                                    tvTwoHint.setTextColor(Color.parseColor("#ea5544"));
                                    tvTwoHint.setText("验证码输入错误");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    private void setVerifica(TextView tvVerify) {
        mCountDownTimerUtils = new CountDownTimerUtils(tvVerify, 60000, 1000);
        mCountDownTimerUtils.start();
    }
    /**
     * 禁止键盘弹出
     */
    private void forbidKeyBoard () {
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(tvPhone, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void configFocusable () {
        tvPhone.setFocusable(true);
        tvPhone.setFocusableInTouchMode(true);
        tvPhone.requestFocus();//获取焦点 光标出现
    }
}
